package me.qi.kancha.security.grant.custom.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.qi.kancha.applet.vwork.VWorkApi;
import me.qi.kancha.dto.core.AccountDTO;
import me.qi.kancha.dto.enums.AccountStatus;
import me.qi.kancha.dto.enums.AccountType;
import me.qi.kancha.security.grant.custom.CustomAuthService;
import me.qi.kancha.security.grant.custom.CustomAuthServiceTag;
import me.qi.kancha.service.AccountService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * 企业微信网页授权登录
 */
@Component
@CustomAuthServiceTag
public class VWorkAuthoriztionService implements CustomAuthService {

    private static final String GRANT_TYPE = "vwork";

    private final VWorkApi workApi;

    private final AccountService accountService;

    public VWorkAuthoriztionService(VWorkApi workApi, AccountService accountService) {
        this.workApi = workApi;
        this.accountService = accountService;
    }

    @Override
    public String getGrantType() {
        return GRANT_TYPE;
    }

    @Override
    public Authentication authorization(OAuth2Request oAuth2Request) throws InvalidGrantException {
        //微信登录
        String appId = oAuth2Request.getClientId();
        String code = oAuth2Request.getRequestParameters().get("code");
        if (ObjectUtils.isEmpty(code)) {
            throw new InvalidGrantException("vwork验证模式必须传入code参数");
        }
        String userId = null;
        try {
            userId = workApi.getUserInfo(appId, code);
        } catch (Exception e) {
            throw new InvalidGrantException("企业微信Api异常："+ e.getMessage());
        }
        if (ObjectUtils.isEmpty(userId)) {
            throw new InvalidGrantException("未获取到企业微信userId");
        }
        //微信用户是否存在appid & openid
        String u = String.format("%s:%s", appId, userId);
        LambdaQueryWrapper<AccountDTO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AccountDTO::getUsername, u);
        AccountDTO accountDTO = accountService.getOne(wrapper);
        if (accountDTO == null) {
            //不存在新增
            accountDTO = new AccountDTO();
            accountDTO.setUsername(u);
            accountDTO.setType(AccountType.VWORK);
            accountDTO.setStatus(AccountStatus.NORMAL);
            accountService.save(accountDTO);
        }
        return new UsernamePasswordAuthenticationToken(accountDTO, null, null);
    }
}
